package com.jsoft.showcontacts;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.view.View;
import android.widget.ImageView;

public class PhotoViewBinder2_3 implements
		SimpleCursorAdapter_DelegateViewBinder {
	SimpleCursorAdapter.ViewBinder delegate;
	ContentResolver contentResolver;

	public PhotoViewBinder2_3() {
		delegate = null;
	}

	public void setViewBinderDelegate(ViewBinder delegate) {
		this.delegate = delegate;
	}

	public void setContentResolver(ContentResolver contentResolver) {
		this.contentResolver = contentResolver;
	}

	public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
		if (cursor.getColumnName(columnIndex).equals(
				ContactsContract.Contacts.PHOTO_ID)
				&& view instanceof ImageView) {
			ImageView iv = (ImageView)view;
			iv.setImageBitmap(null);
			
			int idIndex = cursor.getColumnIndex("_id");
			if (idIndex < 0)
				return false;
			
			Uri contactUri = ContentUris.withAppendedId(
					ContactsContract.Contacts.CONTENT_URI, cursor.getInt(idIndex));

			Uri photoUri = Uri.withAppendedPath(contactUri,
					ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);

			Cursor photoCursor = contentResolver
					.query(photoUri,
							new String[] { ContactsContract.CommonDataKinds.Photo.PHOTO },
							null, null, null);
			if (photoCursor != null && photoCursor.moveToFirst()) {
				byte[] data = photoCursor.getBlob(0);
				Bitmap bmp = BitmapFactory.decodeByteArray(data,0,data.length);
				iv.setImageBitmap(bmp);
			}
			if (photoCursor != null)
				photoCursor.close();
			return true;
		}

		if (delegate != null)
			return delegate.setViewValue(view, cursor, columnIndex);
		return false;
	}

}
